import * as seedrandom from 'seedrandom';

export let random;

export const randomSeed = (seed: number) => {
  random = seedrandom(seed);
};

export const distribute = (value: number, probabilities: [any, number][]) => {
  const total = probabilities.reduce((t, [_, p]) => t+p, 0);
  if (total === 0) {
    // assume equal probabilities
    return probabilities[Math.floor(probabilities.length*value)][0];
  }
  for (let i = 0; i < probabilities.length; ++i) {
    const [choice, p] = probabilities[i];
    value -= p / total;
    if (value <= 0)
      return choice;
  }
  // should never happen if value <= 1, but in case of rounding errors..
  return probabilities[probabilities.length-1][0];
};

export const randomChoice = (values: any[]) => {
  return values[Math.floor(values.length*random())];
};

export const shuffle = (values: any[]) => {
  const rest = [...values];
  let res = [];
  while (rest.length) {
    const i = Math.floor(random()*rest.length);
    res = [...res, ...rest.splice(i, 1)];
  }
  return res;
};

export const randomBetweenInclusive = (a, b) => {
  if (a > b) return a;
  return a + Math.floor(random() * (b-a+1));
};

export const dieNormal = (max, n) => {
  return Array.from({length: n}, () => Math.floor(random()*max/n)).reduce((a, b) => a + b);
};
